package org.romzzz.gwtclassifieds.client.ui;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.VBoxLayout;

/**
 * This is a popup dialog replicating the {@link MessageBox#prompt(String, String) prompt} method but that can be extended to fit other needs.
 */
public abstract class StandardPrompt extends Dialog {
	
	protected TextField<String> entry;
	
	/**
	 * Construct the prompt but does not automatically show the popup. You have to use the {@link Dialog#show() show} method.
	 * @param title the title of the prompt
	 */
	public StandardPrompt(String title) {
		super();
		setLayout(new VBoxLayout());
		entry = new TextField<String>();
		entry.setWidth(225);
		setHeading(title);
		setDraggable(false);
		setResizable(false);
		add(entry);
		setBodyStyleName("pad-text");
		setHideOnButtonClick(true);
		setModal(true);
		setButtons(Dialog.OK);
		setWidth(250);
		Button ok = getButtonById(Dialog.OK);
		ok.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				onOK(entry.getValue());
			}
		});
		entry.addKeyListener(new KeyListener() {
			public void componentKeyPress(ComponentEvent event) {
				if (event.getKeyCode() == 13) { 
					hide();
					onOK(entry.getValue());
				}
			}
		});
		setFocusWidget(entry);
	}
	
	/**
	 * This method is called when clicking OK or pressing enter while typing in the text field.
	 * 
	 * @param value the text field value
	 */
	public abstract void onOK(final String value) ;
	
}
